package handler

import (
	"api/pkg"
	__ "api/proto"
	"api/request"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"path/filepath"
)

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewUserClient(conn)
	login, err := c1.Login(c, &__.LoginRequest{
		Tel:      req.Tel,
		Password: req.Password,
	})
	token, _ := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: uint(login.Id)})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": token,
		"msg":  "登录成功",
	})
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file.Size > 20*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "文件过大 上传失败",
			"data": nil,
		})
		return
	}
	ext := filepath.Ext(file.Filename)
	if ext != ".Mp4" && ext != ".MOV" {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "文件类型错误 重新上传",
			"data": nil,
		})
		return
	}
	uuid := uuid.NewString()
	dst := "./static/upload" + uuid + filepath.Ext(file.Filename)
	c.SaveUploadedFile(file, dst)

	pkg.UploadOss(dst, file.Filename)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": pkg.GetOssFileUrl(file.Filename),
	})
}
